/*
Atmel fuse programming

BODLEVEL = 2V7
OCDEN = [ ]
JTAGEN = [ ]
SPIEN = [X]
WDTON = [ ]
EESAVE = [X]
BOOTSZ = 4096W_7000
BOOTRST = [ ]
CKDIV8 = [ ]
CKOUT = [ ]
SUT_CKSEL = EXTXOSC_8MHZ_XX_16KCK_65MS

EXTENDED = 0xFD (valid)
HIGH = 0xD1 (valid)
LOW = 0xFF (valid)
*/

#include <avr/io.h>
#include <avr/cpufunc.h>
#include <avr/pgmspace.h>
#include <stdio.h>

#include "tests.h"

void setup() {
	// Set ports for minimum invasiveness
	DDRA = 0b00000000;
	PORTA = 0b00000000;
	DDRB = 0b00000001; // Set PB0 as an output for 2 reasons: To control the wait state enable, and to use SPI (this is the SS pin)
	PORTB = 0b00000000;
	DDRC = 0b00000000;
	PORTC = 0b00000000;
	DDRD = 0b00000000;
	PORTD = 0b00000000;
	DDRE = 0b00000010;
	PORTE = 0b00000000;
	DDRF = 0b00000000;
	PORTF = 0b00000000;
	DDRG = 0b00000000;
	PORTG = 0b00000000;
	DDRH = 0b00000000;
	PORTH = 0b00000000;
	DDRJ = 0b00000000;
	PORTJ = 0b00000000;
	DDRK = 0b00000000;
	PORTK = 0b00000000;
	DDRL = 0b00000000;
	PORTL = 0b00000000;
}

static int menu()
{
	do {
		printf_P( PSTR(
		"\n\n\n"
		"Choose a test mode:\n"
		"1)  Voltages\n"
		"2)  Basic functionality\n"
		"3)  Memory tests\n"
		"4)  CPU test\n"
		"5)  VDC test\n"
		"6)  Sound test\n"
		"7)  Input test\n"
		"8)  External video/audio test (NTSC)\n"
		"9)  External video/audio test (PAL)\n"
		) );
		char c = getchar();
		if( c >= '1' && c <= '9' )
		{
			return c - '0';
		}
		while( c != '\n' )
		{
			c = getchar();
		}
	}
	while( true );
}


void loop() {
	setup(); // Keep the system in a known state

	// put your main code here, to run repeatedly:
	switch( menu() )
	{
		case 1:
		doVoltageTest();
		break;
		case 2:
		doBasicTests();
		break;
		case 3:
		doMemTests();
		break;
		case 4:
		CPUTest();
		break;
		case 5:
		basicVDCTest() &&
		vramTest() &&
		graphicsVDCTest();
		break;
		case 6:
		soundTest();
		break;
		case 7:
		checkInput();
		break;
		case 8:
		doExtVideoTestNTSC();
		break;
		case 9:
		doExtVideoTestPAL();
		break;
	}
}
